<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form
            ref="queryForm"
            :model="queryParams"
            :inline="true"
            :label-position="'right'"
          >
            <el-form-item label="水质类别分布" prop="type">
              <el-radio-group
                v-model="queryParams.type"
                size="medium"
                @change="tepeChange"
              >
                <el-radio-button label="按月"></el-radio-button>
                <el-radio-button label="按年"></el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label=""
              prop="riverid"
              v-if="queryParams.type == '按月'"
            >
              <el-date-picker
                v-model="times"
                :type="selectType"
                :value-format="dataValueType"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :key="selectType"
                @change="TimePicker"
                :clearable="false"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="" prop="riverid" v-else>
              <el-date-picker
                v-model="yeartype"
                value-format="yyyy"
                type="year"
                placeholder="选择开始年"
              >
              </el-date-picker>

              <el-date-picker
                v-model="yeartypeb"
                type="year"
                value-format="yyyy"
                placeholder="选择结束年"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              label="考核类型："
              prop="controlLevelCode"
              class="times"
            >
              <el-checkbox-group v-model="queryParams.controlLevelCode">
                <el-checkbox
                  v-for="city in dict.type.sys_assse_type"
                  :label="city.value"
                  :key="city.value"
                  >{{ city.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
                style="padding: 10px"
                >查询</el-button
              >
              <!-- <el-button @click="resetQuery" style="padding: 10px">
              <i class="iconfont icon-saoba"></i>
              清除
            </el-button> -->
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="never">
          <div slot="header">
            <ul>
              <li>
                优三占比前三{{ periodText }}:
                {{ alldatas.excellentThreeListTop3 }}
              </li>
              <li>
                劣五占比前三{{ periodText }}:
                {{ alldatas.inferiorFiveListTop3 }}
              </li>
              <li>超标污染物：{{ alldatas.cbItemList }}</li>
            </ul>
          </div>
          <div
            id="charOne"
            ref="charOne"
            style="height: 450px; width: 100%"
          ></div>
          <div class="water-quality-table">
            <el-table :data="tableData" border style="width: 100%">
              <!-- 行标题列 -->
              <el-table-column label="水质级别\时间" width="120" align="center">
                <template #default="scope">
                  {{ scope.row.level }}
                </template>
              </el-table-column>

              <!-- 时间列（循环渲染） -->
              <el-table-column
                v-for="(time, index) in chartData.xAxisData"
                :key="index"
                :label="time"
                align="center"
              >
                <template #default="scope">
                  {{ scope.row.data[time] }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from "dayjs";
import getTime from "@/utils/getTime.js";
import { updateDate, updateTime, updateTimeB } from "@/utils/ruoyi";
import dateUtil from "@/utils/dateUtil.js";
import {
  getQualitySummary,
  getQualitySummaryYear,
} from "@/api/riverGeneralMange/riverGeneralMange";
export default {
  name: "waterQuality",

  dicts: ["sys_assse_type"],
  data() {
    return {
      timer: new Date().getTime(),
      queryParams: {
        type: "按月",
        controlLevelCode: ["0"],
      },
      // 选择的类型
      selectType: "daterange",
      dataValueType: "yyyy-MM-dd",
      times: "",
      query: {
        startTime: "",
        endTime: "",
      },
      alldatas: {
        excellentThreeListTop3: [],
        inferiorFiveListTop3: [],
        cbItemList: [],
      },
      // 第一个echarts数据
      charDataa: {},
      // 第二个echarts数据
      charDatab: {},

      yeartype: new Date().getFullYear() - 2 + "",
      yeartypeb: new Date().getFullYear() + "",

      checkedCities: ["0"],

      isIndeterminate: true,
      // 模拟的数据，实际使用时可从接口获取
      chartData: {
        xAxisData: [
          "2024-05",
          "2024-06",
          "2024-07",
          "2024-08",
          "2024-09",
          "2024-10",
          "2024-11",
          "2024-12",
          "2025-01",
          "2025-02",
          "2025-03",
        ],
        // 优Ⅲ个数（柱状图，左 Y 轴）
        excellentIIICount: [10, 4, 1, 6, 4, 9, 9, 11, 12, 12, 10],
        // 劣Ⅴ个数（柱状图，左 Y 轴）
        poorVCount: [0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0],
        // 优Ⅲ占比（折线图，右 Y 轴，百分比形式，这里用小数模拟，实际可处理成百分比）
        excellentIIIRatio: [
          0.9, 0.4, 0.1, 0.6, 0.4, 0.9, 0.9, 1.0, 1.0, 1.0, 0.9,
        ],
        inferiorfiveproporlist: [
          0.9, 0.4, 0.1, 0.6, 0.4, 0.9, 0.9, 1.0, 1.0, 1.0, 0.9,
        ],
      },
      // 表格数据，结构可根据实际调整，这里设计为每个水质级别对象包含级别名称和各月数据的对象
      tableData: [],
      // 月份表头数据，按顺序排列
      months: [
        "2024-05",
        "2024-06",
        "2024-07",
        "2024-08",
        "2024-09",
        "2024-10",
        "2024-11",
        "2024-12",
        "2025-01",
        "2025-02",
        "2025-03",
      ],
      periodText: "月份", // 默认为“月份”，切换按年时改为“年份”
    };
  },
  created() {
    // const weekRange = dateUtil.getRecentWeek();
    // this.times = [weekRange.start, weekRange.end];
  },
  mounted() {
    this.tepeChange("按月");
    // this.initChart();
    // this.init();
  },
  methods: {
    init() {},

    // 水质类别切换
    tepeChange(e) {
      this.times = [];
      // 关键：根据切换类型更新标题文本
      this.periodText = e === "按月" ? "月份" : "年份";
      console.log(">>>", e);
      // e == "按日"
      //   ? (this.selectType = "daterange")
      //   : (this.selectType = "monthrange");
      // e == "按日"
      //   ? (this.dataValueType = "yyyy-MM-dd")
      //   : (this.dataValueType = "yyyy-MM");
      if (e == "按月") {
        // this.selectType = "monthrange";
        if (this.times.length == 0) {
          this.dataValueType = "yyyy-MM";
          // 结束时间：当前日期（格式与原项目的formatDate保持一致）
          const today = dayjs().format("YYYY-MM-DD"); // 假设原formatDate输出是"YYYY-MM-DD"格式
          // 起始时间：当前日期往前推6个月
          const sixMonthsAgo = dayjs()
            .subtract(6, "month")
            .format("YYYY-MM-DD");
          this.times = [sixMonthsAgo, today];
        }

        this.query.startTime = this.times[0];
        this.query.endTime = this.times[1];
        this.getQualitySummary();
      } else {
        // this.selectType = "monthrange";
        this.dataValueType = "yyyy";
        const threeMonths = dateUtil.getRecentThreeMonths();
        // this.times = [threeMonths.start, threeMonths.end];
        this.query.startTime = this.yeartype;
        this.query.endTime = this.yeartypeb;
        this.getQualitySummaryYear();
      }
    },
    // 监听时间选择的变化
    TimePicker(val) {
      if (this.times) {
        this.query.startTime = this.times[0];
        this.query.endTime = this.times[1];
      }
    },
    //搜索
    handleQuery() {
      // this.init();
      if (this.queryParams.type == "按月") {
        // this.tepeChange("按月");
        this.query.startTime = this.times[0];
        this.query.endTime = this.times[1];
        this.getQualitySummary();
      } else {
        // this.tepeChange("按年");
        this.query.startTime = this.yeartype;
        this.query.endTime = this.yeartypeb;
        this.getQualitySummaryYear();
      }
    },
    //重置、清除表单
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
    },
    // 优三劣五总结（月）
    getQualitySummary() {
      let query = {
        startTime: this.query.startTime,
        endTime: this.query.endTime,
        controlLevelCode: this.queryParams.controlLevelCode.join(","),
      };
      getQualitySummary(query).then((res) => {
        if (res.code == 200) {
          console.log(">>>月月越", res);
          this.alldatas.excellentThreeListTop3 =
            res.data.excellentThreeListTop3.join(",");
          this.alldatas.inferiorFiveListTop3 =
            res.data.inferiorFiveListTop3.join(",");
          this.alldatas.cbItemList = res.data.cbItemList.join(",");
          this.chartData.xAxisData = res.data.dataTimeList;
          this.chartData.excellentIIICount = res.data.excellentThreeCountList;
          this.chartData.poorVCount = res.data.inferiorFiveCountList;
          this.chartData.excellentIIIRatio = res.data.excellentThreeProporList;
          this.chartData.inferiorfiveproporlist =
            res.data.inferiorFiveProporList;
          this.formatTableData(
            res.data.dataTimeList,
            res.data.excellentThreeProporList,
            res.data.inferiorFiveProporList
          );
          this.initChart();
        }
      });
    },
    // 优三劣五总结（年）
    getQualitySummaryYear() {
      let query = {
        startTime: this.query.startTime,
        endTime: this.query.endTime,
        controlLevelCode: this.queryParams.controlLevelCode.join(","),
      };
      getQualitySummaryYear(query).then((res) => {
        if (res.code == 200) {
          // this.charData = res.data;
          this.alldatas.excellentThreeListTop3 =
            res.data.excellentThreeListTop3.join(",");
          this.alldatas.inferiorFiveListTop3 =
            res.data.inferiorFiveListTop3.join(",");
          this.alldatas.cbItemList = res.data.cbItemList.join(",");
          this.chartData.xAxisData = res.data.dataTimeList;
          this.chartData.excellentIIICount = res.data.excellentThreeCountList;
          this.chartData.poorVCount = res.data.inferiorFiveCountList;
          this.chartData.excellentIIIRatio = res.data.excellentThreeProporList;
          this.chartData.inferiorfiveproporlist =
            res.data.inferiorFiveProporList;
          this.formatTableData(
            res.data.dataTimeList,
            res.data.excellentThreeProporList,
            res.data.inferiorFiveProporList
          );
          this.initChart();
        }
      });
    },
    formatTableData(time, data1, data2) {
      // 1. 生成表头时间列表
      const timeList = time || [];

      // 2. 处理第一行：I-III类占比
      const excellentPropor = data1 || [];
      const firstRow = {
        level: "I-III类占比(%)",
        data: {},
      };
      timeList.forEach((time, index) => {
        // 占比转百分比（接口是小数则乘100，这里接口是"0"这类字符串，先转数字再处理）
        const ratio = (Number(excellentPropor[index]) * 100).toFixed(2);
        firstRow.data[time] = ratio === "0.00" ? "--" : ratio;
      });

      // 3. 处理第二行：劣V类占比
      const inferiorPropor = data2 || [];
      const secondRow = {
        level: "劣V类占比(%)",
        data: {},
      };
      timeList.forEach((time, index) => {
        const ratio = (Number(inferiorPropor[index]) * 100).toFixed(2);
        secondRow.data[time] = ratio === "0.00" ? "--" : ratio;
      });

      // 4. 组装最终表格数据
      this.tableData = [firstRow, secondRow];
    },
    // echarts图
    initChart() {
      let color = [
        "#0CD2E6",
        "#3751E6",
        "#FFC722",
        "#886EFF",
        "#008DEC",
        "#114C90",
        "#00BFA5",
      ];
      // 1. 对优Ⅲ占比数组做兜底：确保是数组，元素非数字则设为0
      const excellentRatioData = (this.chartData.excellentIIIRatio || []).map(
        (item) => {
          const num = Number(item); // 转为数字（处理接口返回字符串格式的数字）
          return isNaN(num) ? 0 : num * 100; // 非数字则设为0，避免NaN显示
        }
      );

      // 2. 对劣Ⅴ占比数组做兜底：同上
      const inferiorRatioData = (
        this.chartData.inferiorfiveproporlist || []
      ).map((item) => {
        const num = Number(item);
        return isNaN(num) ? 0 : num * 100;
      });

      let option = {
        color: color,
        title: {
          text: "水质相关数据统计", // 图表标题，可根据需求修改
          left: "center",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        legend: {
          data: ["优Ⅲ占比", "劣Ⅴ占比", "优Ⅲ个数", "劣Ⅴ个数"],
          top: "5%",
        },
        xAxis: {
          type: "category",
          data: this.chartData.xAxisData,
          axisLabel: {
            interval: 0,
            rotate: 30, // 横轴标签旋转，避免重叠
          },
        },
        yAxis: [
          {
            type: "value",
            name: "个数（个）",
            min: 0,
            max: 12,
            // axisLabel: {
            //   formatter: "{value} 个",
            // },
          },
          {
            type: "value",
            name: "占比（%）",
            min: 0,
            max: 100,
            axisLabel: {
              formatter: "{value} %",
            },
          },
        ],
        series: [
          {
            name: "优Ⅲ占比",
            type: "line",
            yAxisIndex: 1, // 使用右侧 Y 轴
            data: excellentRatioData, // 转为百分比数值
            symbol: "circle",
            lineStyle: {
              color: "green",
            },
            label: {
              show: true,
              position: "top",
            },
          },
          {
            name: "劣Ⅴ占比",
            type: "line",
            yAxisIndex: 1, // 使用右侧 Y 轴
            data: inferiorRatioData, // 转为百分比数值, // 可根据实际劣Ⅴ占比数据填充，这里模拟都为0
            symbol: "circle",
            lineStyle: {
              color: "red",
            },
            label: {
              show: true,
              position: "top",
            },
            // 隐藏该系列图例（因为劣Ⅴ占比数据可能为0，视觉上可隐藏，若有数据可显示）
            showSymbol: false,
          },
          {
            name: "优Ⅲ个数",
            type: "bar",
            data: this.chartData.excellentIIICount,
            itemStyle: {
              color: "green",
            },
            label: {
              show: true,
              position: "top",
              // formatter: "{value} 个",
            },
          },
          {
            name: "劣Ⅴ个数",
            type: "bar",
            data: this.chartData.poorVCount,
            itemStyle: {
              color: "red",
            },
            label: {
              show: true,
              position: "top",
              // formatter: "{value} 个",
            },
          },
        ],
      };
      // let maChar = echarts.init(document.getElementById("waterQuality"));
      let maChar = echarts.init(this.$refs.charOne);
      maChar.setOption(option);
      window.addEventListener("resize", function () {
        maChar.resize();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
//@import url(); 引入公共css类
#panel {
  padding-bottom: 0px;
  min-height: calc(100% - 20px);
  margin: 0;
  .topCen {
    height: 400px;
    display: flex;
    div {
      height: 100%;
    }
    .charA {
      width: 35%;
    }
    .charB {
      width: 35%;
    }
    .topTable {
      width: 30%;
    }
  }
  .botCen {
    height: 300px;
    padding-top: 20px;
    .charC {
      width: 100%;
      height: 100%;
    }
  }
  .el-card {
    margin: 10px;
  }

  .queryForm .el-card__body {
    padding: 0 20px !important;
  }
}
</style>
